算法设计与分析 快速排序的递归实现算法

输入:先输入进行合并排序元素的个数,然后依次随机输入(或随机生成)每个数字

输出:元素排序后的结果。

示例:输入:8  9  1  2  4  8  6  15  8,输出:1  2  4  6  8  8  9  15

 

代码中包含两种,一种是普通快排,一种是生成随机数的快排

 

//快速排序
#include<iostream>
#include <algorithm>
using namespace std;
template<class Type>
int Partition(Type a[],int p,int r)
{
    //完整代码在GitHub上
	//https://github.com/Jxcup/Course_Algorithm_Analysis-Design/blob/main/QuickSort_iteration.cpp

}
template<class Type>
void QuickSort(Type a[],int p,int r)
{
	if(p<r)
	{
		int q=Partition(a,p,r);
		QuickSort(a,p,q-1);
		QuickSort(a,q+1,r);
	}
}


#include <algorithm>
template<class Type>
int Partition(Type a[],int p,int r)
{
	int i=p,j=r+1;
	Type x=a[p];
	while(i<j)
	{
		while(a[++i]<x&&i<r);
		while(a[--j]>x);
		if(i>=j)break;
		swap(a[i],a[j]);
	}
	a[p]=a[j];
	a[j]=x;
	return j;

}
template<class Type>
int RandomizedPartition(Type a[],int p,int r)
{
	int i=random()%(r-p)+p;
	swap(a[i],a[p]);
	return Partition(a,p,r);
}
template<class Type>
void RandomizedQuickSort(Type a[],int p,int r)
{
	if(p<r){
		int q=RandomizedPartition(a,p,r);
		RandomizedQuickSort(a,p,q-1);
		RandomizedQuickSort(a,q+1,r);
	}
}

int main()
{
	int n, data[100];
	cout << "请输入数组的长度" << endl;
	cin >> n;
	cout << "请输入数组" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> data[i];
	}
	RandomizedQuickSort(data,0,n-1);
	for (int i = 0; i < n; i++)
	{
		cout << data[i] << "  ";
	}
	cout << endl;
	system("pause");
	return 0;
}

 

 

 

 

 

 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值